<script setup>
import { ref, onMounted } from 'vue'
import { useGoodsStore } from '@/stores/modules/GoodsStore.js'
const goodsStore = useGoodsStore()
// 搜索关键值
const goodsName = ref()
// 分类对应商品列表
const children = ref([])

onMounted(async () => {
  await goodsStore.saveCategoryList()
  children.value = goodsStore.getCategoryChildren()
})
// 高亮标记
const activeId = ref(null)
const handleSwitch = (categoryId) => {
  activeId.value = categoryId
  children.value = goodsStore.getCategoryChildren(categoryId)
}
</script>

<template>
  <div class="category">
    <van-nav-bar title="全部分类" />
    <div class="search">
      <van-search
        autocomplete="off"
        background="#f1f1f2"
        show-action
        v-model="goodsName"
        shape="round"
        placeholder="请输入搜索关键词"
        @search="$router.push(`/searchList?goodsName=${goodsName}`)"
      >
        <template #action>
          <div @click="$router.push(`/searchList?goodsName=${goodsName}`)">
            搜索
          </div>
        </template>
      </van-search>
    </div>
    <div class="category-container">
      <div class="navbar">
        <ul>
          <li
            :class="{
              'category-name': true,
              active: activeId === item.category_id
            }"
            v-for="item in goodsStore.categoryList"
            :key="item.category_id"
            @click="handleSwitch(item.category_id)"
          >
            <a href="#" :class="{ active: activeId === item.category_id }">{{
              item.name
            }}</a>
          </li>
        </ul>
      </div>
      <div class="category-items">
        <van-grid :column-num="3" :border="false" class="item-container">
          <van-grid-item
            v-for="item in children"
            :key="item.category_id"
            :text="item.name"
            @click="$router.push(`/searchList/${item.category_id}`)"
          >
            <van-image :src="item.image.external_url" />
            <p>{{ item.name }}</p>
          </van-grid-item>
        </van-grid>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.category {
  .category-container {
    display: flex;
    justify-content: space-between;
    .navbar {
      ul {
        height: 100vh;
        overflow: auto;
      }
    }
    .category-name {
      width: 85px;
      height: 45px;
      background: #f3f3f3;
      vertical-align: middle;
      text-align: center;
      &.active {
        background: #ffffff;
      }
      a {
        display: block;
        color: #444;
        font-size: 12px;
        line-height: 45px;
        &.active {
          color: #fb442f;
        }
      }
    }
    .category-items {
      height: 100vh;
      margin: 0 auto;
      overflow: auto;
      p {
        font-size: 12px;
      }
    }
  }
}
</style>
